<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="角色名称：">
      <el-input v-model="formInline.user" placeholder="请输入角色名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>

  <el-row justify="space-between" class="mb-4">
    <el-col :span="10">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button
          type="danger"
          :disabled="selectedRoleId.length === 0"
          @click="batchDelete"
      >批量删除</el-button>
    </el-col>
  </el-row>

  <el-table
      :data="roleList.list"
      border
      style="width: 100%; margin-top: 15px;"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection"></el-table-column>
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="roleName" label="角色名称" />
    <el-table-column prop="description" label="描述" />
    <el-table-column prop="create_time" label="创建时间"/>
    <el-table-column label="操作" width="240">
      <template #default="scope">
        <el-button type="primary" text @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger" text @click="openDeleteDialog(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="pagetable.pageNum"
      v-model:page-size="pagetable.pageSize"
      :page-sizes="[5, 10, 15, 50]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="roleList.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="420px"
      @open="dialogOpen"
      @close="resetFormAndTree"
  >
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="授权">
        <el-tree
            ref="roleTree"
            :data="menuTree"
            :props="treeProps"
            :check-strictly="checkstrictly"
            show-checkbox
            node-key="menu_id"
            @check="treeCheckChange"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>

  <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="320px"
  >
    <p>确定要删除角色「{{ deleteRoleName }}」吗？</p >
    <template #footer>
      <el-button @click="deleteDialogVisible = false">取消</el-button>
      <el-button type="danger" @click="confirmDelete">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

// 树组件引用
const roleTree = ref();
const checkstrictly = ref(false); // 树勾选严格模式
const selectedRoleId = ref([]);   // 批量删除的角色ID集合

// Vue实例代理（用于调用axios）
const { proxy } = getCurrentInstance();

// 树配置（label对应菜单名称字段）
const treeProps = { label: "name" };

// 分页参数
const pagetable = ref({
  pageNum: 1,
  pageSize: 5
});

// 查询表单（角色名称过滤）
const formInline = ref({ user: '' });

// 分页事件：触发数据重新加载
const handleSizeChange = (val) => {
  pagetable.value.pageSize = val;
  initData();
};
const handleCurrentChange = (val) => {
  pagetable.value.pageNum = val;
  initData();
};

// 角色列表（分页结构：{ list: [], total: 0 }）
const roleList = ref({
  list: [],  // 角色数据数组
  total: 0   // 总条数
});

// 搜索过滤：基于角色名称模糊匹配（可选，若需要本地过滤可保留）
const searchKey = ref('');
const filteredRoleList = computed(() => {
  if (!searchKey.value) return roleList.value.list;
  return roleList.value.list.filter(role =>
      role.roleName.includes(searchKey.value)
  );
});

// 弹窗打开时的逻辑（控制树的严格勾选模式）
const dialogOpen = () => {
  checkstrictly.value = dialogTitle.value !== "新增角色";
};

// 批量删除逻辑
const batchDelete = () => {
  ElMessageBox.confirm(
      `确定要删除选中的${selectedRoleId.value.length}个角色吗？`,
      '确认删除',
      { type: 'warning' }
  ).then(() => {
    const loading = ElLoading.service({ text: '删除中...' });
    proxy.$axios.delete(`/RoleController/batchDelete`, {
      data: { batchDeleteList: selectedRoleId.value }
    }).then((res) => {
      loading.close();
      if (res.data.code == 0) {
        ElMessage.success('批量删除成功');
        selectedRoleId.value = [];
        initData(); // 关键：重新加载最新数据
      } else {
        ElMessage.error(res.data.msg || '删除失败');
      }
    }).catch(() => {
      loading.close();
      ElMessage.error('网络错误');
    });
  });
};

// 表格选中事件：收集选中的角色ID
const handleSelectionChange = (selection) => {
  selectedRoleId.value = selection.map(item => item.id);
};

// 弹窗相关状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增角色');
const currentRoleId = ref(null); // 当前编辑的角色ID

// 表单数据（新增/编辑）
const form = ref({
  role_id: null,
  roleName: '',
  selectedMenuId: [], // 选中的菜单ID集合
  description: ''
});

// 弹窗关闭时重置表单和树（新增方法）
const resetFormAndTree = () => {
  form.value.roleName = '';
  form.value.description = '';
  form.value.selectedMenuId = [];
  roleTree.value?.setCheckedKeys([]); // 重置树勾选
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 表单校验规则
const rules = ref({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度为 2-20 字符', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '描述最多 100 字符', trigger: 'blur' }
  ]
});
const formRef = ref(null); // 表单引用（用于校验）

// 删除弹窗状态
const deleteDialogVisible = ref(false);
const deleteRoleName = ref(''); // 待删除角色名称
const deleteRoleId = ref(null); // 待删除角色ID

// 查询按钮：触发搜索（调用initData并传递参数）
const onSubmit = () => {
  searchKey.value = formInline.value.user;
  initData(); // 直接调用initData，由initData处理参数
  ElMessage.info('执行查询');
};

// 新增按钮：打开弹窗
const handleAdd = () => {
  dialogTitle.value = '新增角色';
  currentRoleId.value = null;
  resetFormAndTree(); // 重置表单和树
  dialogVisible.value = true;
};

// 编辑按钮：加载角色数据并打开弹窗
const openEditDialog = (row) => {
  dialogTitle.value = '编辑角色';
  currentRoleId.value = row.id;
  form.value = { ...row }; // 复制行数据到表单

  // 加载角色已授权的菜单
  proxy.$axios.get("/RoleMenuController/getRoleMenuList", {
    params: { role_id: row.id }
  }).then((res) => {
    if (res.data.code == 0) {
      const menuIds = res.data.data;
      form.value.selectedMenuId = menuIds;
      roleTree.value.setCheckedKeys(menuIds); // 回显树勾选
      checkstrictly.value = false;
    }
  });

  dialogVisible.value = true;
};

// 提交表单（新增/编辑）
const submitForm = async () => {
  try {
    await formRef.value.validate(); // 表单校验
    const requestData = {
      role_name: form.value.roleName,
      description: form.value.description,
      selectedMenuList: form.value.selectedMenuId
    };

    if (currentRoleId.value) {
      // 编辑逻辑：带role_id
      requestData.role_id = currentRoleId.value;
      await proxy.$axios.put("/RoleController/updateRole", requestData)
          .then((serverData)=>{
            if(serverData.data.code==0){
              ElMessage.success('角色编辑成功！');
            }else {
              ElMessage.error(serverData.data.msg)
            }
          })
    }else {
      // 新增逻辑
      await proxy.$axios.post("/RoleController/insertRole", requestData).then((serverData)=>{
        if(serverData.data.code==0){

          ElMessage.success('角色新增成功！');

        }else {
          ElMessage.error(serverData.data.msg)
        }})


    }
    dialogVisible.value = false;
    initData(); // 新增/编辑后刷新数据
  } catch (error) {
    ElMessage.error('表单校验失败，请检查输入！');
  }
};

// 打开删除弹窗
const openDeleteDialog = (row) => {
  deleteRoleName.value = row.roleName;
  deleteRoleId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除（仅调用接口，由initData刷新数据）
const confirmDelete = () => {
  proxy.$axios.delete(`/RoleController/deleteRole/${deleteRoleId.value}`)
      .then((res) => {
        if (res.data.code == 0) {
          deleteDialogVisible.value = false;
          ElMessage.success('角色删除成功！');
          initData(); // 关键：重新加载最新数据
        }else{
          ElMessage.error(res.data.msg)
          deleteDialogVisible.value = false;
        }
      })
      .catch(() => {
        ElMessage.error('删除失败，请重试');
      });
};

// 菜单树数据加载
const menuTree = ref([]);
const menuList = () => {
  proxy.$axios.get("/api/v1/getMenuList")
      .then((res) => {
        if (res.data.code == 0) {
          menuTree.value = res.data.data;
        }
      });
};

// 树勾选事件：合并选中和半选中的节点
const treeCheckChange = () => {
  const checkedKeys = roleTree.value.getCheckedKeys();
  const halfCheckedKeys = roleTree.value.getHalfCheckedKeys();
  // 合并半选中和选中的节点（去重）
  form.value.selectedMenuId = [...new Set([...halfCheckedKeys, ...checkedKeys])];
};

// 初始化数据（分页查询，核心修复点）
const initData = () => {
  proxy.$axios.get(
      `/RoleController/getRoleList/${pagetable.value.pageNum}/${pagetable.value.pageSize}`,
      { params: { role_name: formInline.value.user } } // 传递搜索参数
  ).then((res) => {
    if (res.data.code == 0) {
      // 严格处理后端响应，避免结构错误
      const { list = [], total = 0 } = res.data.data || {};
      roleList.value.list = list.map(role => ({
        id: role.role_id,
        roleName: role.role_name,
        description: role.description,
        create_time: role.create_time,
        selectedMenuId: []
      }));
      roleList.value.total = total; // 同步总条数
    } else {
      ElMessage.error(res.data.msg || '数据加载失败');
    }
  }).catch((error) => {
    ElMessage.error('网络错误，请稍后重试');
    console.error(error);
  });
};

// 页面挂载时初始化
onMounted(() => {
  initData();   // 加载角色列表
  menuList();   // 加载菜单树
});
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>